package com.peaksport.framework.extend.jpa;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryInformation;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

/**
 * 
 * @author jinbin_guo 2019年4月19日
 *
 * @param <T>
 * @param <S>
 * @param <ID>
 */

public class PKJpaRespositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable>
		extends JpaRepositoryFactoryBean<T, S, ID> {

	public PKJpaRespositoryFactoryBean(Class<? extends T> repositoryInterface) {
		super(repositoryInterface);
	}

	@Override
	// 重写createRepositoryFactory方法，用当前的CustomRepositoryFactory创建实例
	protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
		return new PKJpaRepositoryFactory(entityManager); // 该类见下面的定义
	}

	// 定义一个私有的静态类，并继承JpaRepositoryFactory
	private static class PKJpaRepositoryFactory extends JpaRepositoryFactory {

		// 构造函数
		public PKJpaRepositoryFactory(EntityManager entityManager) {
			super(entityManager);
		}

		@SuppressWarnings({ "rawtypes", "unchecked" })
		protected PKJpaRepositoryImpl<?, ?> getTargetRepository(
				RepositoryInformation information, EntityManager entityManager) {
			// 获得当前自定义类的实现
			return new PKJpaRepositoryImpl(information.getDomainType(), entityManager);
		}


		@Override
		protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {// 获得当前自定义类的类型
			return PKJpaRepositoryImpl.class;
		}
	}

}
